package com.taiyo.modules.api.controller;

import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.taiyo.common.utils.JwtUtils;
import com.taiyo.common.utils.R;
import com.taiyo.common.utils.RedisUtils;
import com.taiyo.common.validator.Assert;
import com.taiyo.modules.api.annotation.AuthIgnore;
import com.taiyo.modules.sys.entity.SysUserEntity;
import com.taiyo.modules.sys.service.SysUserService;

import java.util.HashMap;
import java.util.Map;

/**
 * API登录授权
 */
@RestController
@RequestMapping("/api")
public class ApiLoginController {
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private JwtUtils jwtUtils;
	@Autowired
	private RedisUtils redisUtil;
	/**
	 * 登录
	 */
	@AuthIgnore
	@PostMapping("/login")
	public R login(String username, String password) {
		Assert.isBlank(username, "手机号不能为空");
		Assert.isBlank(password, "密码不能为空");

		// 用户登录
		SysUserEntity user = sysUserService.queryByUserName(username);
		if (user == null)
		{
			user = sysUserService.queryByMobile(username);
		}
		// 账号不存在、密码错误
		if (user == null || !user.getPassword().equals(new Sha256Hash(password, user.getSalt()).toHex())) {
			return R.error("账号或密码不正确");
		}
		// 账号锁定
		if (user.getStatus() == 0) {
			return R.error("账号已被锁定,请联系管理员");
		}
		// 生成token
		String token = jwtUtils.generateToken(user.getUserId());

		Map<String, Object> map = new HashMap<>();
		map.put("token", token);
		map.put("expire", jwtUtils.getExpire());
		map.put("user", user);
		redisUtil.set(token, user, jwtUtils.getExpire());
		return R.ok(map);
	}

}
